package com.baseproject.datasource.local.database.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;

import com.baseproject.BaseProjectAppCofig;
import com.baseproject.datasource.local.database.dao.annotation.DbField;
import com.baseproject.datasource.local.database.dao.annotation.DbTable;
import com.baseproject.util.LogUtils;

import java.lang.reflect.Field;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    // 数据库版本号
    private static final int DATABASE_VERSION = 5;

    // 数据库名
    private static final String DATABASE_NAME = "baseProject.db";

    public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        List<Class> entityClasses = BaseProjectAppCofig.getInstance().getDatabaseModelClasses();
        for (Class entity : entityClasses) {
            createTable(entity, db);
        }
    }

    private <T> void createTable(Class<T> entity, SQLiteDatabase db) {
        String sqlCreate = getCreateTableSql(entity);
        if (!TextUtils.isEmpty(sqlCreate)) {
            //建表
            db.execSQL(sqlCreate);
        }
    }

    /**
     * 得到建表语句
     * @param clazz 指定类
     * @return sql语句
     */
    protected String getCreateTableSql(Class<?> clazz) {
        StringBuilder sb = new StringBuilder();
        sb.append("create table if not exists ").append(getTableName(clazz)).append(" (id  INTEGER PRIMARY KEY AUTOINCREMENT, ");

        //得到成员变量数组
        Field[] columnFields = clazz.getFields();
        for (Field field : columnFields) {
            field.setAccessible(true);
        }
        for (Field field : columnFields) {
            //找到列名与bean对象的成员变量的映射关系
            DbField anno = field.getAnnotation(DbField.class);

            String fieldName = field.getName();
            String fieldType = field.getType().getName();
            if (anno != null && TextUtils.isEmpty(anno.value())) {
                //说明注解中内容为空，表示域名称和数据库表字段名一样
                if (fieldName.equalsIgnoreCase("_id") || fieldName.equalsIgnoreCase("id")) {
                    continue;
                } else {
                    sb.append(fieldName).append(DBUtils.getColumnType(fieldType)).append(", ");
                }
            } else if (anno != null && !TextUtils.isEmpty(anno.value())) {
                //说明注解中内容非空，表示域名称和数据库表字段名可能不同，通过注解指定表字段名
                if (fieldName.equalsIgnoreCase("_id") || fieldName.equalsIgnoreCase("id")) {
                    continue;
                } else {
                    sb.append(anno.value()).append(DBUtils.getColumnType(fieldType)).append(", ");
                }
            }
        }
        int len = sb.length();
        sb.replace(len - 2, len, ")");
        LogUtils.d(" result is " + sb.toString());
        return sb.toString();
    }

    public <T> String getTableName(Class<T> entity) {
        return TextUtils.isEmpty(entity.getAnnotation(DbTable.class).value())
                ? DBUtils.getTableName(entity)
                : entity.getAnnotation(DbTable.class).value();
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        LogUtils.d("[onUpgrade] oldVersion = " + oldVersion + " newVersion = " + newVersion);
    }

    private void upgradeTable(SQLiteDatabase db, String tableName) {

    }
}
